package com.lonewalker.sparrow.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lonewalker
 */
public class HttpContextUtil {

    public HttpContextUtil() {
    }

    public static String getHeader(String head) {
        return ObjectUtil.isNotNull(getHttpServletRequest()) ? getHttpServletRequest().getHeader(head) : "";
    }

    public static HttpServletRequest getHttpServletRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return ObjectUtil.isNotNull(requestAttributes) ? ((ServletRequestAttributes) requestAttributes).getRequest() : null;
    }

    public static Map<String, String> getParameterMap(HttpServletRequest request) {
        Enumeration<String> parameters = request.getParameterNames();
        Map<String, String> params = new HashMap<>(10);

        while (parameters.hasMoreElements()) {
            String parameter = parameters.nextElement();
            String value = request.getParameter(parameter);
            if (StrUtil.isNotBlank(value)) {
                params.put(parameter, value);
            }
        }

        return params;
    }

    public static String getLanguage() {
        String defaultLanguage = "zh-CN";
        HttpServletRequest request = getHttpServletRequest();
        if (ObjectUtil.isNotNull(request)) {
            defaultLanguage = request.getHeader("Accept-Language");
        }
        return defaultLanguage;
    }
}
